package leetcode;

public class _0445 {
    /**
     *两数相加 II
     */
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if(l1==null){
                return l2;
            }
            if(l2==null){
                return l1;
            }
            ListNode a =  reverse(l1);
            ListNode b = reverse(l2);
            ListNode ans = new ListNode();
            ListNode p0 = ans;
            int n = 0;
            while(a!=null||b!=null||n!=0){
                if(a!=null){
                    n += a.val;
                }
                if(b!=null){
                    n+=b.val;
                }
                p0.next = new ListNode(n%10);
                p0 = p0.next;
                n=n/10;
                if(a!=null){
                    a = a.next;
                }
                if(b!=null){
                    b=b.next;
                }
            }
            ans=reverse(ans.next);
            return ans;
        }
        public ListNode reverse(ListNode head){
            ListNode dump = new ListNode(0,head);
            ListNode p0= dump;
            ListNode pre = null,cur = p0.next;
            while(cur!=null){
                ListNode nxt = cur.next;
                cur.next = pre;
                pre = cur;
                cur = nxt;
            }
            return pre;
        }

    }
    private class ListNode {
        ListNode next;
        int val;
        ListNode(){}
        ListNode(int val){
            this.val=val;
        }
        ListNode(int val, ListNode next){
            this.val = val;
            this.next = next;
        }
    }
}
